import { Auth } from "@d8d-appcontainer/auth";
import { APIClient } from "@d8d-appcontainer/api";
import { getAuthConfig, getApiConfig } from "../config/config.ts";

let authInstance: Auth | null = null;

export async function initializeAuth(): Promise<Auth> {
  const apiConfig = getApiConfig();
  const authConfig = getAuthConfig();

  const client = new APIClient({
    scope: "user",
    config: {
      serverUrl: apiConfig.serverUrl,
      type: "http",
      workspaceKey: apiConfig.workspaceKey,
    },
  });

  return await new Promise((resolve) => {
    client.on("connected", async () => {
      console.log("Connected to API server");
      authInstance = new Auth(client, {
        jwtSecret: authConfig.jwtSecret,
        initialUsers: authConfig.initialUsers,
        singleSession: true,
      });

      await authInstance.initialize();

      resolve(authInstance);
    });
  });
}

export function getAuth(): Auth {
  if (!authInstance) {
    throw new Error("Auth service not initialized");
  }
  return authInstance;
}
